package cn.airfei.netty.nettyexample.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @description:
 * @author: air
 * @create: 2021-01-18 16:06
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取客户端数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest){

            System.out.println("msg 类型="+msg.getClass());
            System.out.println("客户端地址:"+ctx.channel().remoteAddress());

            String uri = ((HttpRequest) msg).uri();
            System.out.println("uri:"+uri);
            if (uri.equals("/favicon.ico")){
                System.out.println("请求了服务器过滤的资源:"+uri);
                return;
            }


            // 回复信息给浏览器
            ByteBuf content= Unpooled.copiedBuffer("hello , 我是服务器", CharsetUtil.UTF_8);

            // 创建一个http响应
            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

            // 将构建的response返回
            ctx.writeAndFlush(defaultFullHttpResponse);

        }
    }
}
